import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { InventoryTransferService } from './inventory-transfer.service';
import { InventoryTransferDto } from './models';
import { TransferDataService } from '../shared/services/transfer-data.service';
import { OutOrderService } from '../OutOrder/out-order.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-inventory-transfer-detail',
  templateUrl: './inventory-transfer-detail.component.html',
  styleUrls: ['./inventory-transfer-detail.component.scss'],
  standalone: true,
  imports: [CommonModule]
})
export class InventoryTransferDetailComponent implements OnInit {
  transfer: InventoryTransferDto | null = null;
  isLoading = true;
  currentTab: string = 'detail'; // 默认显示调拨明细

  // 新增：调出弹窗相关
  isOutOrderModalOpen = false;
  outOrderData: any = null;
  isSaving = false; // 保存状态
  orderNo: string = '自动生成'; // 出库单号显示

  // 新增：调入弹窗相关
  isIntOrderModalOpen = false;
  orderNoint: string = '自动生成';
  intOrderInDate: string = '';
  intOrderOperator: string = '';
  intOrderRemarks: string = '';
  intOrderDetails: any[] = [];
  inOrderData: any = null;

  // 出库记录mock数据
  outOrderRecords: any[] = [];
  get totalQuantity() {
    return this.outOrderRecords.reduce((sum, r) => sum + (r.outOrderNumber || 0), 0);
  }
  get totalAmount() {
    return this.outOrderRecords.reduce((sum, r) => sum + (r.outOrderPrice || 0), 0);
  }

  // 出库记录合计数量（兼容不同字段名）
  get outStockedQuantity(): number {
    return this.outOrderRecords.reduce((sum, r) => sum + (r.outOrderNumber || r.merchandiseNumber || 0), 0);
  }

  // 统计某明细行的已出库数量（根据货品编号匹配出库记录）
  getDetailOutStockedNumber(detail: any): number {
    return this.outOrderRecords
      .filter(r => (r.merchandiseNo === detail.merchandiseNo || r.merchandiseNo === detail.MerchandiseNo))
      .reduce((sum, r) => sum + (r.outOrderNumber || r.merchandiseNumber || 0), 0);
  }

  constructor(
    private route: ActivatedRoute,
    private inventoryTransferService: InventoryTransferService,
    private router: Router,
    private transferDataService: TransferDataService,
    private outOrderService: OutOrderService, // 新增注入
    private http: HttpClient
  ) {}

  ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id');
    console.log('详情页id:', id);
    if (id) {
      this.inventoryTransferService.get(id).subscribe({
        next: (data) => {
          console.log('详情数据:', data);
          this.transfer = data;
          this.isLoading = false;
        },
        error: (err) => {
          console.error('详情接口报错', err);
          this.isLoading = false;
        }
      });
      // 新增：页面加载时获取出库记录
      this.outOrderService.getOutStockOrderWithDetailsByInventoryTranId(id).subscribe({
        next: (res: any) => {
          if (Array.isArray(res) && res.length > 0) {
            this.outOrderData = { outStockOrder: res[0].outStockOrder };
            this.outOrderRecords = res[0].details || [];
          } else {
            this.outOrderData = { outStockOrder: null };
            this.outOrderRecords = [];
          }
        },
        error: (err) => {
          this.outOrderData = { outStockOrder: null };
          this.outOrderRecords = [];
        }
      });
    }
  }

  getTotalQuantity(): number {
    const list = this.transfer?.merchandiseList || this.transfer?.details || [];
    return list.reduce((sum, d) => sum + Number(d.merchandiseNumber || d.MerchandiseNumber || 0), 0);
  }

  getTotalAmount(): number {
    const list = this.transfer?.merchandiseList || this.transfer?.details || [];
    return list.reduce((sum, d) => sum + Number(d.merchandisePrice || d.MerchandisePrice || 0), 0);
  }

  goToOutOrder() {
    const id = this.route.snapshot.paramMap.get('id');
    if (!id) return;
    this.outOrderService.createFromInventoryTransfer(id).subscribe({
      next: (outOrder) => {
        this.outOrderData = outOrder;
        // 只显示真实单号，不显示“自动生成”
        this.orderNo = this.outOrderData.outStockOrder?.orderNo || '';
        // 出库记录tab数据源赋值为details
        this.outOrderRecords = this.outOrderData.details || [];
        // 保证inventoryTransferType字段小写，删除大写字段，和后端DTO一致
        if (this.outOrderData.outStockOrder) {
          this.outOrderData.outStockOrder.inventoryTransferType =
            this.outOrderData.outStockOrder.inventoryTransferType ||
            this.outOrderData.outStockOrder.InventoryTransferType ||
            '货品调拨';
          delete this.outOrderData.outStockOrder.InventoryTransferType;
        }
        if (this.outOrderData.details) {
          this.outOrderData.details.forEach((d: any) => d.currentOutNumber = 0);
        }
        this.isOutOrderModalOpen = true;
      },
      error: (err) => {
        alert('生成出库单失败');
      }
    });
  }

  closeOutOrderModal() {
    this.isOutOrderModalOpen = false;
    this.outOrderData = null;
  }

  saveOutOrder() {
    // 校验：不允许本次出库数量大于未出库数量
    let valid = true;
    if (this.outOrderData.details) {
      for (let d of this.outOrderData.details) {
        if (d.currentOutNumber > (d.merchandiseNumber || d.MerchandiseNumber)) {
          valid = false;
          break;
        }
      }
    }
    if (!valid) {
      alert('不允许大于未出库数量!');
      return;
    }
    // TODO: 提交保存逻辑
    this.isOutOrderModalOpen = false;
  }

  // 保存按钮调用的方法
  saveOrder() {
    this.isSaving = true;
    // 保证inventoryTransferType字段小写，删除大写字段，和后端DTO一致
    if (this.outOrderData.outStockOrder) {
      this.outOrderData.outStockOrder.inventoryTransferType =
        this.outOrderData.outStockOrder.inventoryTransferType ||
        this.outOrderData.outStockOrder.InventoryTransferType ||
        '货品调拨';
      delete this.outOrderData.outStockOrder.InventoryTransferType;
    }
    // 构造和后端DTO一致的请求体
    const outStockOrder = this.outOrderData.outStockOrder;
    const payload = {
      inventoryTranId: outStockOrder.inventoryTranId,
      orderNo: outStockOrder.orderNo,
      inventoryTransferType: outStockOrder.inventoryTransferType || '货品调拨',
      inventoryTransferNo: outStockOrder.inventoryTransferNo,
      inventoryTransferOUT: outStockOrder.inventoryTransferOUT,
      outDateTime: outStockOrder.outDateTime,
      inventoryTransferOperator: outStockOrder.inventoryTransferOperator,
      remarks: outStockOrder.remarks,
      Details: this.outOrderData.details // 注意大写D
    };
    console.log('最终提交的payload:', payload);
    this.outOrderService.saveOutStockOrderWithDetails(payload).subscribe(
      res => {
        // 保存成功后用后端返回的orderNo更新显示
        this.orderNo = res.orderNo || '自动生成';
        alert('保存成功！');
        this.isSaving = false;
        this.isOutOrderModalOpen = false;
        // 可根据需要刷新页面或做其它操作
      },
      err => {
        let msg = '保存失败！';
        if (err && err.error && err.error.message) {
          msg += '\n' + err.error.message;
        } else if (err && err.message) {
          msg += '\n' + err.message;
        }
        alert(msg);
        this.isSaving = false;
        console.error('保存失败:', err);
      }
    );
  }

  removeDetail(index: number) {
    if (this.outOrderData && this.outOrderData.details) {
      this.outOrderData.details.splice(index, 1);
    }
  }

  getTotalNumber() {
    if (!this.outOrderData?.details) return 0;
    return this.outOrderData.details.reduce((sum, d) => sum + (d.merchandiseNumber || d.MerchandiseNumber || 0), 0);
  }

  getTotalCurrentOutNumber() {
    if (!this.outOrderData?.details) return 0;
    return this.outOrderData.details.reduce((sum, d) => sum + (Number(d.outOrderNumber) || 0), 0);
  }

  getTotalOutOrderAmount() {
    if (!this.outOrderData?.details) return 0;
    return this.outOrderData.details.reduce((sum, d) => sum + ((Number(d.outOrderNumber) || 0) * (Number(d.merchandiseINPrice) || 0)), 0);
  }

  // 新增：模板安全转换数字
  toNumber(val: any): number {
    return Number(val) || 0;
  }

  // tab切换方法，切换到出库记录时自动加载数据
  onTabChange(tab: string) {
    this.currentTab = tab;
    if (tab === 'in') {
      const id = this.route.snapshot.paramMap.get('id');
      if (id) {
        this.http.get<any[]>(`/api/app/stock-in-order/with-details-by-inventory-tran-id/${id}`).subscribe({
          next: (res) => {
            if (Array.isArray(res) && res.length > 0) {
              this.inOrderData = res[0].stockInOrder;
              this.intOrderDetails = res[0].details || [];
            } else {
              // 写入死数据
              this.inOrderData = {
                orderNoint: 'RK202407110001',
                intDateTime: '2024-07-11T10:00:00',
                inventoryTransferInt: '葫芦岛',
                inventoryTransferOperator: '张三'
              };
              this.intOrderDetails = [
                {
                  MerchandiseName: '苹果手机',
                  InOrderNumber: 10,
                  InOrderPrice: 100,
                  // 其他字段可按需补充
                }
              ];
            }
          },
          error: (err) => {
            // 写入死数据
            this.inOrderData = {
              orderNoint: 'RK202407110001',
              intDateTime: '2024-07-11T10:00:00',
              inventoryTransferInt: '葫芦岛',
              inventoryTransferOperator: '张三'
            };
            this.intOrderDetails = [
              {
                MerchandiseName: '苹果手机',
                InOrderNumber: 10,
                InOrderPrice: 100,
                // 其他字段可按需补充
              }
            ];
          }
        });
      }
    }
    // 原有的出库tab逻辑
    if (tab === 'out') {
      const id = this.route.snapshot.paramMap.get('id');
      if (id) {
        this.outOrderService.getOutStockOrderWithDetailsByInventoryTranId(id).subscribe({
          next: (res: any) => {
            // 兼容返回数组结构
            if (Array.isArray(res) && res.length > 0) {
              this.outOrderData = { outStockOrder: res[0].outStockOrder };
              this.outOrderRecords = res[0].details || [];
            } else {
              this.outOrderData = { outStockOrder: null };
              this.outOrderRecords = [];
            }
          },
          error: (err) => {
            this.outOrderData = { outStockOrder: null };
            this.outOrderRecords = [];
            alert('获取出库记录失败');
          }
        });
      }
    }
  }

  goToIntOrder() {
    // 自动生成入库单号（可替换为后端接口）
    const now = new Date();
    this.orderNoint = 'RK' + now.getFullYear() + (now.getMonth()+1).toString().padStart(2,'0') + now.getDate().toString().padStart(2,'0') + now.getHours().toString().padStart(2,'0') + now.getMinutes().toString().padStart(2,'0') + now.getSeconds().toString().padStart(2,'0');
    this.intOrderInDate = '';
    this.intOrderOperator = '';
    this.intOrderRemarks = '';
    this.intOrderDetails = (this.transfer.details || this.transfer.merchandiseList || []).map(d => ({ ...d }));
    this.isIntOrderModalOpen = true;
  }
  closeIntOrderModal() {
    this.isIntOrderModalOpen = false;
  }

  saveIntOrder() {
    const payload = {
      inventoryTranId: 0,
      orderNoint: this.orderNoint,
      inventoryTransferType: this.transfer.InventoryTransferType,
      inventoryTransferNo: this.transfer.InventoryTransferNo,
      inventoryTransferInt: this.transfer.InventoryTransferIN,
      intDateTime: this.intOrderInDate ? new Date(this.intOrderInDate).toISOString() : null,
      inventoryTransferOperator: this.intOrderOperator,
      remarks: this.intOrderRemarks,
      details: this.intOrderDetails
    };
    console.log('提交payload:', payload); // 调试用
    this.http.post('/api/app/stock-in-order/with-details', payload).subscribe(
      res => {
        alert('保存成功！');
        this.isIntOrderModalOpen = false;
      }
    );
  }

  // 入库明细合计数量
  getTotalInNumber() {
    if (!this.intOrderDetails) return 0;
    return this.intOrderDetails.reduce((sum, d) => sum + (Number(d.InOrderNumber) || 0), 0);
  }

  // 入库明细合计金额
  getTotalInOrderAmount() {
    if (!this.intOrderDetails) return 0;
    return this.intOrderDetails.reduce((sum, d) => sum + ((Number(d.InOrderNumber) || 0) * (Number(d.InOrderPrice) || 0)), 0);
        }

  // 入库状态（未入库/部分入库/已入库 x/y）
  getInStockStatus(): string {
    const total = this.intOrderDetails.reduce((sum, d) => sum + (Number(d.MerchandiseNumber) || 0), 0);
    const inStock = this.intOrderDetails.reduce((sum, d) => sum + (Number(d.InOrderNumber) || 0), 0);
    if (inStock === 0) {
      return `未入库 ${inStock}/${total}`;
    } else if (inStock < total) {
      return `部分入库 ${inStock}/${total}`;
    } else {
      return `已入库 ${inStock}/${total}`;
    }
  }

  goBack() {
    this.router.navigate(['/inventoryTransfer']);
  }
} 